<template>
  <div class="audit-log-management">
    <!-- 查询条件 -->
    <el-card class="search-card">
      <el-form :model="queryForm" inline>
        <el-form-item label="用户ID">
          <el-input v-model="queryForm.userId" placeholder="请输入用户ID" clearable />
        </el-form-item>
        <el-form-item label="操作类型">
          <el-select v-model="queryForm.operation" placeholder="请选择操作类型" clearable>
            <el-option label="数据权限检查" value="DATA_SCOPE_CHECK" />
            <el-option label="社区权限验证" value="COMMUNITY_PERMISSION_CHECK" />
            <el-option label="用户权限验证" value="USER_PERMISSION_CHECK" />
            <el-option label="资源访问控制" value="RESOURCE_ACCESS_CONTROL" />
          </el-select>
        </el-form-item>
        <el-form-item label="操作结果">
          <el-select v-model="queryForm.result" placeholder="请选择操作结果" clearable>
            <el-option label="成功" :value="1" />
            <el-option label="失败" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="queryForm.timeRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 统计信息 -->
    <el-card class="statistics-card">
      <el-row :gutter="20">
        <el-col :span="6">
          <div class="stat-item">
            <div class="stat-title">总操作次数</div>
            <div class="stat-value">{{ statistics.totalCount || 0 }}</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-item">
            <div class="stat-title">成功次数</div>
            <div class="stat-value success">{{ statistics.successCount || 0 }}</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-item">
            <div class="stat-title">失败次数</div>
            <div class="stat-value error">{{ statistics.failCount || 0 }}</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-item">
            <div class="stat-title">成功率</div>
            <div class="stat-value">{{ statistics.successRate || 0 }}%</div>
          </div>
        </el-col>
      </el-row>
    </el-card>

    <!-- 操作栏 -->
    <el-card class="operation-card">
      <el-row :gutter="10">
        <el-col :span="1.5">
          <el-button type="primary" @click="handleExport" v-auth="'audit:log:export'">
            <el-icon><Download /></el-icon>
            导出日志
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="warning" @click="handleCleanExpired" v-auth="'audit:log:clean'">
            <el-icon><Delete /></el-icon>
            清理过期日志
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger" @click="handleBatchDelete" v-auth="'audit:log:delete'">
            <el-icon><Delete /></el-icon>
            批量删除
          </el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 审计日志列表 -->
    <el-card class="table-card">
      <el-table 
        v-loading="tableLoading" 
        :data="auditLogList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="userId" label="用户ID" width="100" />
        <el-table-column prop="operation" label="操作类型" width="150">
          <template #default="{ row }">
            <el-tag :type="getTagType(getOperationTagType(row.operation))">
              {{ getOperationText(row.operation) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="target" label="操作目标" min-width="200" />
        <el-table-column label="操作结果" width="100">
          <template #default="{ row }">
            <el-tag :type="getTagType(row.result === 1 ? 'success' : 'danger')">
              {{ row.result === 1 ? '成功' : '失败' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="ipAddress" label="IP地址" width="120" />
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="handleViewDetail(row)">
              查看详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 详情弹窗 -->
    <el-dialog 
      v-model="detailVisible" 
      title="审计日志详情" 
      width="800px"
      :before-close="handleCloseDetail"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="日志ID">{{ currentLog.id }}</el-descriptions-item>
        <el-descriptions-item label="用户ID">{{ currentLog.userId }}</el-descriptions-item>
        <el-descriptions-item label="操作类型">{{ getOperationText(currentLog.operation) }}</el-descriptions-item>
        <el-descriptions-item label="操作结果">
          <el-tag :type="getTagType(currentLog.result === 1 ? 'success' : 'danger')">
            {{ currentLog.result === 1 ? '成功' : '失败' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="操作目标" :span="2">{{ currentLog.target }}</el-descriptions-item>
        <el-descriptions-item label="详细信息" :span="2">{{ currentLog.details }}</el-descriptions-item>
        <el-descriptions-item label="IP地址">{{ currentLog.ipAddress }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ formatDateTime(currentLog.createTime) }}</el-descriptions-item>
        <el-descriptions-item label="用户代理" :span="2">{{ currentLog.userAgent }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <!-- 清理过期日志弹窗 -->
    <el-dialog 
      v-model="cleanVisible" 
      title="清理过期日志" 
      width="500px"
      :before-close="handleCloseClean"
    >
      <el-form :model="cleanForm" label-width="120px">
        <el-form-item label="保留天数">
          <el-input-number 
            v-model="cleanForm.days" 
            :min="1" 
            :max="365"
            placeholder="请输入保留天数"
          />
        </el-form-item>
        <el-form-item label="说明">
          <div class="clean-tip">
            将删除指定天数之前的所有审计日志，此操作不可恢复，请谨慎操作！
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCloseClean">取消</el-button>
          <el-button type="warning" @click="confirmCleanExpired">确认清理</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessageBox } from 'element-plus'
import { showMessage, getTagType } from '@/utils/message'
import { Download, Delete } from '@element-plus/icons-vue'
import { getAuditLogPage, getAuditStatistics, cleanExpiredLogs, exportAuditLogs, batchDeleteAuditLogs } from '@/api/property/auditLog'

// 响应式数据
const tableLoading = ref(false)
const auditLogList = ref([])
const selectedLogs = ref([])
const detailVisible = ref(false)
const cleanVisible = ref(false)
const currentLog = ref({})
const statistics = ref({})

// 查询表单
const queryForm = reactive({
  userId: '',
  operation: '',
  result: '',
  timeRange: []
})

// 清理表单
const cleanForm = reactive({
  days: 90
})

// 分页信息
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 获取操作类型标签类型
const getOperationTagType = (operation) => {
  const typeMap = {
    'DATA_SCOPE_CHECK': 'primary',
    'COMMUNITY_PERMISSION_CHECK': 'success',
    'USER_PERMISSION_CHECK': 'warning',
    'RESOURCE_ACCESS_CONTROL': 'info'
  }
  return typeMap[operation] || 'default'
}

// 获取操作类型文本
const getOperationText = (operation) => {
  const textMap = {
    'DATA_SCOPE_CHECK': '数据权限检查',
    'COMMUNITY_PERMISSION_CHECK': '社区权限验证',
    'USER_PERMISSION_CHECK': '用户权限验证',
    'RESOURCE_ACCESS_CONTROL': '资源访问控制'
  }
  return textMap[operation] || operation
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return ''
  return new Date(dateTime).toLocaleString()
}

// 查询审计日志列表
const getAuditLogList = async () => {
  try {
    tableLoading.value = true
    
    const params = {
      current: pagination.current,
      size: pagination.size,
      userId: queryForm.userId || undefined,
      operation: queryForm.operation || undefined,
      result: queryForm.result || undefined,
      startTime: queryForm.timeRange?.[0] || undefined,
      endTime: queryForm.timeRange?.[1] || undefined
    }
    
    const response = await getAuditLogPage(params)
    if (response.code === 200) {
      auditLogList.value = response.data.records
      pagination.total = response.data.total
    } else {
      showMessage({ type: 'error', message: response.message || '查询失败' })
    }
  } catch (error) {
    console.error('查询审计日志失败:', error)
    showMessage({ type: 'error', message: '查询失败' })
  } finally {
    tableLoading.value = false
  }
}

// 获取统计信息
const getStatistics = async () => {
  try {
    const params = {
      startTime: queryForm.timeRange?.[0] || undefined,
      endTime: queryForm.timeRange?.[1] || undefined
    }
    
    const response = await getAuditStatistics(params)
    if (response.code === 200) {
      statistics.value = response.data
    }
  } catch (error) {
    console.error('获取统计信息失败:', error)
  }
}

// 查询
const handleSearch = () => {
  pagination.current = 1
  getAuditLogList()
  getStatistics()
}

// 重置
const handleReset = () => {
  Object.assign(queryForm, {
    userId: '',
    operation: '',
    result: '',
    timeRange: []
  })
  pagination.current = 1
  getAuditLogList()
  getStatistics()
}

// 分页大小改变
const handleSizeChange = (size) => {
  pagination.size = size
  pagination.current = 1
  getAuditLogList()
}

// 当前页改变
const handleCurrentChange = (current) => {
  pagination.current = current
  getAuditLogList()
}

// 选择改变
const handleSelectionChange = (selection) => {
  selectedLogs.value = selection
}

// 查看详情
const handleViewDetail = (row) => {
  currentLog.value = { ...row }
  detailVisible.value = true
}

// 关闭详情弹窗
const handleCloseDetail = () => {
  detailVisible.value = false
  currentLog.value = {}
}

// 导出日志
const handleExport = async () => {
  try {
    const params = {
      userId: queryForm.userId || undefined,
      operation: queryForm.operation || undefined,
      result: queryForm.result || undefined,
      startTime: queryForm.timeRange?.[0] || undefined,
      endTime: queryForm.timeRange?.[1] || undefined
    }
    
    const response = await exportAuditLogs(params)
    if (response.code === 200) {
      showMessage({ type: 'success', message: '导出成功' })
      // 这里可以添加文件下载逻辑
    } else {
      showMessage({ type: 'error', message: response.message || '导出失败' })
    }
  } catch (error) {
    console.error('导出失败:', error)
    showMessage({ type: 'error', message: '导出失败' })
  }
}

// 清理过期日志
const handleCleanExpired = () => {
  cleanVisible.value = true
}

// 关闭清理弹窗
const handleCloseClean = () => {
  cleanVisible.value = false
  cleanForm.days = 90
}

// 确认清理过期日志
const confirmCleanExpired = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要清理${cleanForm.days}天之前的审计日志吗？此操作不可恢复！`,
      '确认清理',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await cleanExpiredLogs({ days: cleanForm.days })
    if (response.code === 200) {
      showMessage({ type: 'success', message: `清理成功，共清理${response.data}条记录` })
      cleanVisible.value = false
      getAuditLogList()
      getStatistics()
    } else {
      showMessage({ type: 'error', message: response.message || '清理失败' })
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('清理失败:', error)
      showMessage({ type: 'error', message: '清理失败' })
    }
  }
}

// 批量删除
const handleBatchDelete = async () => {
  if (selectedLogs.value.length === 0) {
    showMessage({ type: 'warning', message: '请选择要删除的日志' })
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的${selectedLogs.value.length}条审计日志吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const logIds = selectedLogs.value.map(log => log.id)
    const response = await batchDeleteAuditLogs(logIds)
    if (response.code === 200) {
      showMessage({ type: 'success', message: '删除成功' })
      getAuditLogList()
      getStatistics()
    } else {
      showMessage({ type: 'error', message: response.message || '删除失败' })
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      showMessage({ type: 'error', message: '删除失败' })
    }
  }
}

// 初始化
onMounted(() => {
  getAuditLogList()
  getStatistics()
})
</script>

<style scoped>
.audit-log-management {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.statistics-card {
  margin-bottom: 20px;
}

.stat-item {
  text-align: center;
  padding: 20px;
}

.stat-title {
  font-size: 14px;
  color: #666;
  margin-bottom: 10px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #333;
}

.stat-value.success {
  color: #67c23a;
}

.stat-value.error {
  color: #f56c6c;
}

.operation-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination-wrapper {
  margin-top: 20px;
  text-align: right;
}

.clean-tip {
  color: #e6a23c;
  font-size: 14px;
  line-height: 1.5;
}

.dialog-footer {
  text-align: right;
}
</style> 